package hc.j2me.ui;

import hc.j2me.util.ImageUtility;

import java.io.IOException;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Layer;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;

public abstract class PressShortPanel {
	public Sprite sprite_shortclick; 
	public boolean isOn = false;
	public boolean isOnWaitingSelect = false;
	protected final int _blockWidth;
	final int cellNum;
	PNGGameCanvas canvas;
	public int pressX, pressY;
	
	public PressShortPanel(final int _blockWidth, PNGGameCanvas canvas, int cellNum){
		this._blockWidth = _blockWidth;
		this.canvas = canvas;
		this.cellNum = cellNum;
	}
	
	protected void buildShortSprite(LayerManager lm, Layer overLayer,
			final int _blockWidth, final int userMouseSplitWidth,
			final int _16, final String[] imgURL) {
		final int width = _blockWidth;
		final int height = _blockWidth * cellNum;
		
		final int[] array = new int[width * height];
		ImageUtility.initBoxAtCell(width, height, ImageUtility.COLOR_TRANS_LAY, array, _blockWidth, userMouseSplitWidth, _16);

		final int[] imgdata = new int[_16 * _16];
		for (int i = 0; i < cellNum; i++) {
			try {
				final Image img = Image.createImage(imgURL[i]);
				img.getRGB(imgdata, 0, _16, 0, 0, _16, _16);
				final int tx = 0 * (_blockWidth) + userMouseSplitWidth;
				final int ty = i * (_blockWidth) + userMouseSplitWidth;
				ImageUtility.drawImage(imgdata, 0, 0, _16, _16, _16, _16, true, tx, ty, width, array);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Image image = ImageUtility.createSafeAlphaImg(array, width, height, array.length, ImageUtility.isHardAlpha);
		sprite_shortclick = new Sprite(image);
		sprite_shortclick.setVisible(false);
		lm.insert(sprite_shortclick, PNGGameCanvas.getLayerIdx(lm, overLayer));
	}
	
	public void dispose(){
		isOn = false;
		isOnWaitingSelect = false;
		sprite_shortclick.setVisible(false);
	}
	
	/**
	 * 
	 * @param idx 付入-1表示没有选择
	 * @return
	 */
	public abstract int actionIconIdx(int idx);
	
	public int pointerReleased(final int x, final int y) {
		final int postionX = sprite_shortclick.getX();
		final int postionY = sprite_shortclick.getY();
		final int width = sprite_shortclick.getWidth();
		
		if(x >= postionX && y >= postionY && x < (postionX + width)){
			final int idx = (y - postionY) / _blockWidth;
			
			return actionIconIdx(idx);
		}
		return actionIconIdx(-1);
	}
}
